const createError = require('http-errors');
const express = require('express');
const bodyParser = require("body-parser")
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const skillsRouter = require('./routes/skills');
const gamesRouter = require('./routes/games');
const authRouter = require('./routes/auth');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/skills', skillsRouter);
app.use('/games', gamesRouter);
app.use('/auth', authRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//解决跨域
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Content-Type")
  res.header("Access-Control-Allow-Methods", "*")
  res.header("Content-Type", "application/json;charset=utf-8")
  next()
});
module.exports = app;

// const express = require("express");
// const app = express();
// const mysql = require("mysql");
//
// app.listen(3001,()=>{
//   console.log("服务器开启3001端口...")
// })


// 创建与数据库的连接
// const db = mysql.createConnection({
//   host:'localhost',
//   user:"root",
//   password:'wan320911',
//   database:"newsql"    //数据库名称
// })
//
// db.connect((err)=>{
//   if(err) throw err;
//   console.log("连接成功");
// })
//
// //getpost就是接口
// app.get("/getList",(req,res)=>{
//   let sql = "select * from student";
//   db.query(sql,(err,result)=>{
//     if(err){
//       console.log(err);
//     }else{
//       //将数据转换为json格式
//       var dataString = JSON.stringify(result);
//       var data = JSON.parse(dataString);
//       res.json({
//         status:'0',
//         msg:data
//       })
//     }
//   })
// })

